﻿package net.wangit.framework.config;

import java.util.HashMap;
import java.util.Map;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.framework.cache.Cache;
import net.wangit.framework.util.CacheUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.ServerAccessException;
import net.wangit.jdbc.util.DBHelper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class Mappings {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.config.Mappings.class);
	private static final String SQL = "select uid,eid from ELEMENT where a=1";//所有ActionElement

	public Mappings() {
	}

	public static boolean contains(String domain, String unitId, String actionId) {
		String key = getKey(unitId, actionId);
		Map mappings = getMappings(domain);
		return mappings.containsKey(key);
	}

	private static Map getMappings(String domain) {
		Map mappings = (Map) getCache().get(domain);
		if (mappings == null) {
			reload(domain);
			return (Map) getCache().get(domain);
		} else {
			return mappings;
		}
	}

	public static synchronized void reload(String domain) {
		Cache cache = getCache();
		cache.clear(domain);
		cache.put(domain, createMappings(domain));
	}

	private static Map createMappings(String domain) {
		Map map = new HashMap();
		DB db = DBHelper.getDomainDB(domain);
		MapList list;
		try {
			list = db.query(Mappings.SQL);
		} catch (Exception e) {
			log.error(
					(new StringBuilder("could not query element in server: "))
							.append(domain).toString(), e);
			throw new ServerAccessException((new StringBuilder(
					"could not query element in server: ")).append(domain)
					.toString());
		}
		for (int i = 0; i < list.size(); i++) {
			Row row = list.getRow(i);
			String key = getKey(row.get("uid"), row.get("eid"));
			map.put(key, null);
		}

		return map;
	}

	private static String getKey(String unitId, String elementId) {
		return (new StringBuilder(String.valueOf(unitId))).append(".").append(
				elementId).toString();
	}

	private static Cache getCache() {
		return CacheUtil.getMappingsCache();
	}

}
